// merchants/addVipcard/index.js
const app = getApp();
const utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0, //0代表新增，其他表示编辑
    startDate: '',
    startTime: '',
    endDate: '',
    endTime: '',
    nowData: '',
    nowtime: '',
    title: '',
    discount: '',
    timeType: 1, //指定时间段；2永久有效
    remark: '',
    gradeid: 0,
    detailpics: [],
    allianceid: 0
  },
  saveVipcard: function() {
    let that = this;
    let startTime = '';
    let endTime = '';
    let param = {};
    let detailpics = that.data.detailpics;
    if (detailpics.length > 0) {
      for (var i = 0; i < detailpics.length; i++) {
        var Index = detailpics[i].lastIndexOf('l/');
        detailpics[i] = detailpics[i].substr(Index + 2, detailpics[i].length);
      }
    }
    detailpics = detailpics.toString();
    if (!that.data.title) {
      that.checkWrite('请填写标题')
      return
    }
    if (!that.data.discount) {
      that.checkWrite('请输入折扣')
      return
    }
    if (that.data.timeType == 2) {
      startTime = that.data.nowData + " " + that.data.nowtime;
      endTime = '2099-12-31 ' + that.data.nowtime;
    }
    if (that.data.timeType == 1) {
      startTime = that.data.startDate + " " + that.data.startTime;
      endTime = that.data.endDate + " " + that.data.endTime;
    }
    if (that.data.gradeid > 0) { //礼包折扣卡
      param = {
        uid: app.globalData.userInfo.Uid,
        title: that.data.title,
        startTime: startTime,
        endTime: endTime,
        discount: parseFloat(that.data.discount),
        timeType: that.data.timeType,
        id: that.data.id,
        remark: that.data.remark,
        DetailPics: detailpics,
        isPackage: 1,
        gradeId: that.data.gradeid
      }
    }
    if (that.data.allianceid > 0) { //联盟礼包会员卡
      param = {
        uid: app.globalData.userInfo.Uid,
        title: that.data.title,
        startTime: startTime,
        endTime: endTime,
        discount: parseFloat(that.data.discount),
        timeType: that.data.timeType,
        id: that.data.id,
        remark: that.data.remark,
        DetailPics: detailpics,
        allianceId: that.data.allianceid
      }
    }
    if (that.data.gradeid <= 0 && that.data.allianceid <= 0) { //商家折扣卡
      param = {
        uid: app.globalData.userInfo.Uid,
        title: that.data.title,
        startTime: startTime,
        endTime: endTime,
        discount: parseFloat(that.data.discount),
        timeType: that.data.timeType,
        id: that.data.id,
        remark: that.data.remark,
        DetailPics: detailpics,
      }
    }
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    wx.request({
      url: app.globalData.host + '/api/Coupon/AddOrUpdateCard',
      data: param,
      method: 'POST',
      success: function(res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '保存成功',
            duration: 5000,
            success(res) {
              if (that.data.allianceid > 0) {
                wx.navigateTo({
                  url: '/merchant/alliance/allianceManager/index?tagindex=3',
                })
              } else {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //获取折扣卡
  getVipCard: function(vipcardId) {
    let that = this;
    let {
      startDate,
      startTime,
      endDate,
      endTime,
      timeType,
      title,
      discount,
      remark,
      detailpics
    } = that.data;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardByStaff?uid=' + app.globalData.userInfo.Uid + '&id=' + vipcardId,
      success: function(res) {
        if (res.data.Code == 0) {
          let vipcardInfo = res.data.Data;
          var detailpics = vipcardInfo.DetailPics;
          var list = [];
          if (detailpics != '') {
            var newDetailPics = detailpics.split(",");
            for (let i = 0; i < newDetailPics.length; i++) {
              list[i] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[i];
            }
          }
          if (res.data.Data) {
            vipcardInfo.EndTime = vipcardInfo.EndTime.substr(0, 10);
            discount = vipcardInfo.Discount;
            title = vipcardInfo.Title;
            timeType = vipcardInfo.TimeType
            endDate = vipcardInfo.EndTime.substr(0, 10);
            endTime = vipcardInfo.EndTime.substr(11, 8);
            startDate = vipcardInfo.StartTime.substr(0, 10);
            startTime = vipcardInfo.StartTime.substr(11, 8);
            remark = vipcardInfo.Remark;
          }
          that.setData({
            discount: discount,
            title: title,
            timeType: timeType,
            endDate: endDate,
            startDate: startDate,
            remark: remark,
            detailpics: list
          })
          that.data.endTime = endTime;
          that.data.startTime = startTime;
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  addDate: function(dataStr, dayCount) {
    var strdate = dataStr; //日期字符串
    var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
    isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000); //日期加1天
    var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());
    return pdate;
  },
  timestateUpdate: function(e) {
    this.setData({
      timeType: e.currentTarget.dataset.timetype
    })
  },
  bindtitle: function(e) {
    this.setData({
      title: e.detail.value
    })
  },
  bindDiscount: function(e) {
    if (e.detail.value < 0 || e.detail.value > 100) {
      this.checkWrite("请输入0-100之间的整数");
      return;
    }
    this.setData({
      discount: e.detail.value
    })
  },
  bindDescVal: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  //填写判断
  checkWrite: function(str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      wx.setNavigationBarTitle({
        title: '编辑会员卡'
      })
      this.getVipCard(options.id);
      this.setData({
        id: options.id
      })
    } else {
      wx.setNavigationBarTitle({
        title: '新建会员卡'
      })
      this.setData({
        id: 0
      })
    }
    if (options.gradeid) {
      this.setData({
        gradeid: options.gradeid
      })
    }
    if (options.allianceid) {
      this.setData({
        allianceid: options.allianceid
      })
    }
    this.CurentTime();
    this.CurentData();
    let startTime = this.data.startDate + this.data.startTime;
    let endDate = this.addDate(startTime, 365);
    let month = '';
    let date = '';
    let newEndDate = '';
    let newDate = endDate.split("-");
    if (newDate[1] < 10) {
      month = '0' + newDate[1]
    } else {
      month = newDate[1]
    }
    if (newDate[2] < 10) {
      date = '0' + newDate[2]
    } else {
      date = newDate[2]
    }
    newEndDate = newDate[0] + '-' + month + '-' + date;
    this.setData({
      endDate: newEndDate,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  /**
   * 上传详细图片
   */

  uploadDetailImage: function(e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    detailPics = that.data.detailpics
    var pics = [];
    if (detailPics.length >= 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })

  },

  //多张图片上传
  uploadimg: function(data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        var detailpics = that.data.detailpics;
        detailpics.push(pic_name);
        that.setData({
          detailpics: detailpics
        })
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },
  /**
   * 长按删除详细图片
   */
  deleteDetailPic: function(e) {
    var that = this;
    var newPics = that.data.detailpics;
    newPics.splice(e.currentTarget.dataset.index, 1);
    that.setData({
      detailpics: newPics
    })
  },

  // 获取当前年月
  CurentData: function() {
    var that = this;
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var clock = year + "-";
    if (month < 10)
      clock += "0";
    clock += month + "-";
    if (day < 10)
      clock += "0";
    clock += day + " ";
    that.setData({
      nowData: clock,
      startDate: clock,
    })
  },
  // 获取当前时间分秒
  CurentTime: function() {
    var that = this;
    var now = new Date();
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds() //秒
    var clock = "";
    if (hh < 10)
      clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    that.data.nowtime = clock;
    that.data.startTime = clock;
  },

  //日期
  bindDateChange: function(e) {
    var date = e.detail.value;
    this.setData({
      startDate: date
    })
  },

  //日期
  bindDateChange1: function(e) {
    var date = e.detail.value;
    this.setData({
      endDate: date
    })
  }  
})